<?php
namespace Home\Controller;
use Think\Controller;

/**
 * 会员账户控制
 */
class UserController extends InitController {

	protected function _initialize()
	{
		parent::_initialize();
		$this->model = D('User');
		
	}

	//会员中心
	public function people_centre(){
		// 获取等级列表
		$level_list = getMemberLevelList();
		
		//判断是否超过了试用天数,超过了返回false,没有返回true
	    $judge_member =  judge_member_probation($this->opt,$this->info);
		$day          =  judge_member_probation($this->opt,$this->info,true);
		
		if($day){
			$this->assign('day', $day);
		}

		$user_level_info = M('User')->where(array("id"=>$this->uid))->field("valid_time,level")->find();

		$this->assign('judge_member', $judge_member);
		$this->assign('user_level_info', $user_level_info);
		$this->assign('level_list', $level_list);
		$this->assign('close_qr', $close_qr);
		$this->display('people_centre');
	}
	//异步修改会员头像
	public function chage_user_thumb () {
		if(IS_AJAX){
			$path = I('path');
			$member_info = $this->info;
			M('User')->where(array('id'=>$member_info['id']))->save(array('thumb'=>$path[0]));
			session('home_member_info.thumb',$path[0]);
		}else{
			return false;
		}
	}
	// 个人中心修改密码等页面
	public function loginbg(){
	
		$this->display('loginbg');
	}

	// 修改昵称
	public function change_name()
	{
		if (IS_AJAX) {
			$username = I('username');	// 会员昵称

			if (empty($username)) {
				$this->ajaxReturn(array('status' => '-1', 'msg' => '新昵称不能为空'));
			}

			if ($this->info['username'] == $username)
			{
				// 没变化直接提示修改成功
				$this->ajaxReturn(array('status' => '1', 'msg' => '新昵称修改成功'));
			}

			$data = array(
				'username' => $username
			);
			$judge = M('user')->where('id = %d',$this->uid)->save($data); 
			if($judge !== false){
				session('home_member_info.username',$username);
				$this->ajaxReturn(array('status' => '1', 'msg' => '新昵称修改成功'));
			}
			else
			{
				$this->ajaxReturn(array('status' => '-1', 'msg' => '修改失败'));
			}
		}
		$this->display('change_name');
	}

	//修改微信号
	public function change_wx()
	{
		if (IS_AJAX) {
			$weixin = I('weixin');	// 微信号

			if (empty($weixin)) {
				$this->ajaxReturn(array('status' => '-1', 'msg' => '微信号不能为空'));
			}

			$data = array(
				'weixin' => $weixin
			);
			$judge = M('user')->where('id = %d',$this->uid)->save($data);
            
			if($judge !== false){
				session('home_member_info.weixin',$weixin);
				$this->ajaxReturn(array('status' => '1', 'msg' => '新微信号修改成功'));
			}
			else
			{
				$this->ajaxReturn(array('status' => '-1', 'msg' => '修改失败'));
			}
		}

		$this->display('change_wx');
	}

	// 更换手机号码
	public function change_mobile()
	{
		$this->display('change_mobile');
	}


	// 升级付费
	public function upgrade()
	{

		// 获取等级列表
		$level_list = getMemberLevelList();

		if (IS_AJAX) {
			$update_level = I('level');

			if (empty($update_level) || empty($level_list[$update_level])) {
				// 请求失败
				$this->ajaxReturn(array('status' => '-1', 'msg' => '请求错误'));
			}else{
				// 付费部分
				$this->ajaxReturn(array('status' => '1', 'msg' => $update_level.' · 购买['.$level_list[$update_level]['level_name'].'] 需要付费'.$level_list[$update_level]['price']));
			}
		}

		$this->assign(array(
			'level' => $level_list,
		));

		$this->display('upgrade');
	}
	
	//支付方式页面展示
	public function paytype(){
		$id = I('id');

		$this->assign(array(
			'id'=>$id
		));
		$this->display('paytype');
	}

	// 用户提现
	public function withdraw()
	{
		$uid = $this->uid;
		$page		= I('page',0,'intval');
		$limit		= '';
		$index		= 10;
		$page_all	= 0;
        //获取页数
		if(!empty($page)){
			$now_page	= ($page + 1); 
			$page_all	= $page * $index;
			$limit		= $page_all.','.$index;
		}else{
			$limit		= '0,10';
		}
	
		// 获取等级列表
		$level_list = getMemberLevelList();
		
		//用户提现记录
		$list = M('Infomoation')->where(array('uid'=>$uid,'type'=>array("in","1,3")))->limit($limit)->order('id DESC')->select();
		if ($list) {
			$status = 1;
			foreach($list as $k=>$v){
				$list[$k]['createtime_str'] = date('Y年m月d日 H:i:s',$v['createtime']);
			}
		} else {
			$status = 0;
		}

		//用于ajax分页
		if (IS_AJAX) {
			return $this->ajaxReturn(array('data'=>$list,'status'=>$status));
		}
		
		$this->assign(array(
			'level' => $level_list,
			'list'=>$list
		));
		$this->display('withdraw');
	}
	
	//支付宝提现
	public function alipay_withdraw(){
		$uid = $this->uid;

		$allmoney = M('UserSpreadIncome')->where(array('spreader'=>$uid))->sum('commission');
		$getmoney = M('WithdrawalApply')->where(array('uid'=>$uid,'status'=>array('neq','-1')))->sum('money');

		// 上一次提现信息 
		// RULE: 申请中或者已完成，优先最新已完成
		$lastInfo = M('WithdrawalApply')->where(array('uid' => $uid, 'paytype' => 2, 'status' => array('NEQ',-1)))->field('name,mobile')->order('status DESC , id DESC')->find();
		
		$lastmoney = $allmoney-($getmoney*100);
		//提现规则
		$withdraw_rule = M('options')->where(array('option_name'=>'withdrawal_rule'))->find();
		//发送邮箱
			
		if(IS_AJAX){
			$money = I('money');
			$mobile = I('mobile');
			
			//提现金额以分做单位
			$money  = round($money,2);
			
			//提现金额判断
			if($money*100 > $lastmoney){
				$withdraw_money = round($lastmoney/100,2);

				if(!$withdraw_money){
					$this->ajaxReturn(array('status'=>'0','msg'=>'没有佣金可以提现'));die;
				}

				$this->ajaxReturn(array('status'=>'0','msg'=>'可提现金额为'.$withdraw_money.'已超过可提现金额'));die;
			}
			
			//手机号码判断
			if(!isMobile($mobile)){
				$this->ajaxReturn(array('status'=>'0','msg'=>'手机号码格式不正确'));die;
			}
			
			//提现规则判断
			if($money < $withdraw_rule['option_value']){
				$this->ajaxReturn(array('status'=>'0','msg'=>'提现金额不能小于'.$withdraw_rule['option_value'].'元'));die;
			}
			
			$data = array(
				'uid'=>$uid,
				'name'=>I('name'),
				'paytype'=>I('paytype'),
				'money'=>$money,
				'mobile'=>I('mobile'),
				'disposetime'=>NOW_TIME,
				'createtime'=>NOW_TIME,		
			);
			
			$ac = M('WithdrawalApply')->add($data);
			
			if($ac){
				//信息中心
                $type = 1;
				
				//支付宝提现发送邮件
				$content = "用户名：{$this->info['username']},手机号码：{$this->info['mobile']};申请支付宝提现({$money}元),<a href='".U('admin/Index/index','','',true)."' target='_blank'>立即登录查看</a>";
				
				//发送邮件
				@send_mail($this->opt['send_mail'],''.$this->opt['site_name'].'支付宝提现','支付宝提现',$content);
				
                information_content($uid,$type,$data);
				$this->ajaxReturn(array('status'=>'1','msg'=>'申请成功','url'=>U('Home/User/withdraw')));
			}else{
				$this->ajaxReturn(array('status'=>'0','msg'=>'申请失败'));
			}
		}
		
		$this->assign(array(
			'lastmoney'=>round($lastmoney/100,2),
			'withdraw_rule'=>$withdraw_rule,
			'lastInfo' => $lastInfo,
		));
		$this->display('alipay_withdraw');
	}
	
	//微信提现
	public function wx_withdraw(){
		$this->display('wx_withdraw');
	}
	
	//银行卡提现
	public function bank_withdraw(){
		//银行卡提现查询银行资料有没有补全
		$bankinfo = M('BankInfo')->where('uid='.$this->uid)->find();
		if(empty($bankinfo)){
			$this->redirect('bank_info');
		}
		
		$uid = $this->uid;
		$allmoney = M('UserSpreadIncome')->where(array('spreader'=>$uid))->sum('commission');
		$getmoney = M('WithdrawalApply')->where(array('uid'=>$uid,'status'=>array('neq','-1')))->sum('money');
		$lastmoney = $allmoney-($getmoney*100);
		
		//提现规则
		$withdraw_rule = M('options')->where(array('option_name'=>'withdrawal_rule'))->find();
		
		if(IS_AJAX){

			$money  = I('money','0');
			$mobile = I('mobile','','trim');
			//提现金额以分做单位
			$money  = round($money,2);
			
			//提现金额判断
			if($money*100 > $lastmoney){
				$withdraw_money = round($lastmoney/100,2);

				if(!$withdraw_money){
					$this->ajaxReturn(array('status'=>'0','msg'=>'没有佣金可以提现'));die;
				}

				$this->ajaxReturn(array('status'=>'0','msg'=>'可提现金额为'.$withdraw_money.'已超过可提现金额'));die;
			}
			
			//手机号码判断
			if(!isMobile($mobile)){
				$this->ajaxReturn(array('status'=>'0','msg'=>'手机号码格式不正确'));die;
			}
			
			//提现规则判断
			if($money < $withdraw_rule['option_value']){
				$this->ajaxReturn(array('status'=>'0','msg'=>'提现金额不能小于'.$withdraw_rule['option_value'].'元'));die;
			}
			
			$data = array(
				'uid'=>$this->uid,
				'name'=>$bankinfo['realname'],
				'paytype'=>I('paytype'),
				'money'=>$money,
				'mobile'=>$mobile,
				'disposetime'=>NOW_TIME,
				'createtime'=>NOW_TIME,				
			);
			
			$ac = M('WithdrawalApply')->add($data);
			
			if($ac){
                //信息中心
                $type = 1;
				
				//银行卡提现升级发送邮件
				$content = "用户名：{$this->info['username']},手机号码：{$this->info['mobile']};申请银行卡提现({$money}元),<a href='".U('admin/Index/index','','',true)."' target='_blank'>立即登录查看</a>";
				
				//发送邮件
				@send_mail($this->opt['send_mail'],''.$this->opt['site_name'].'银行卡提现','银行卡提现',$content);
				
                information_content($uid,$type,$data);
				$this->ajaxReturn(array('status'=>'1','msg'=>'申请成功','url'=>U('Home/User/withdraw')));
			}else{
				$this->ajaxReturn(array('status'=>'0','msg'=>'申请失败'));
			}
		}
		
		$this->assign(array(
			'lastmoney'=>round($lastmoney/100,2),
			'withdraw_rule'=>$withdraw_rule
		));
		$this->display('bank_withdraw');
	}
	
	//修改银行卡信息
	public function bank_info(){
		//银行卡提现查询银行资料有
		$bank = M('BankInfo');
		$bankinfo = $bank->where('uid='.$this->uid)->find();
		
		if(IS_AJAX){
			$data = array(
				'uid'=>$this->uid,
				'realname'=>I('realname'),
				'bankname'=>I('bankname'),
				'payaccount'=>I('payaccount'),
				'bankpath'=>I('bankpath'),
				'createtime'=>NOW_TIME
			);
			
			if(empty($bankinfo)){
				$bool = $bank->add($data);
			}else{
				$bool = $bank->where(array('uid'=>$this->uid))->save($data);
			}
			
			if($bool){
				$this->ajaxReturn(array('status'=>'1','msg'=>'保存成功','url'=>U('Home/User/bank_withdraw')));
			}else{
				$this->ajaxReturn(array('status'=>'0','msg'=>'请填写完整信息'));
			}
		}
		
		$this->assign(array('bankinfo'=>$bankinfo));
		$this->display('bank_info');
	}
	

	//账户明细
	public function account()
	{
		
		$uid = session('home_uid');
		$username = session('home_member_info.username');
		
		//推广总收入
		$totalCommission = M('User_spread_income')->where(array('spreader'=>$uid))->sum('commission');//单位是分
		if($totalCommission){
			$totalCommission = round($totalCommission / 100,2);
		}
		
		//已提现佣金
		$ytx_commission = M('Withdrawal_apply')->where(array('status'=>1,'uid'=>$uid))->sum('money');//单位元
		
		//申请提现处理中金额
		$sqtx_commission = M('Withdrawal_apply')->where(array('status'=>0,'uid'=>$uid))->sum('money');//单位元
		
		//可提现佣金
		$cantx_commission = $totalCommission - $ytx_commission - $sqtx_commission;

		// 佣金列表
		$page         = I('page',0,'intval');
		$limit        = '';
		$index        = 10;
		$page_all     = 0;
		$files        = 'id,title,createtime';
        //获取页数
		if(!empty($page)){
			$now_page = ($page + 1); 
			$page_all = $page * $index;
			$limit    = $page_all.','.$index;
		}else{
			$limit    = '0,10';
		}
		$list = M('Infomoation')->where(array('uid' => $this->uid, 'type' => 2))->order('id desc')->limit($limit)->select();
		//用于ajax分页
		if(IS_AJAX){			
			if (!empty($list)) {
				foreach ($list as $k=>$v) {
					$list[$k]['createtime'] = date('Y-m-d H:i:s',$v['createtime']);
				}
			}
			$this->ajaxReturn(array('data'=>$list,'status'=>'1'));
		}

		$this->assign('list',$list);
		$this->assign('totalCommission',$totalCommission + 0);
		$this->assign('ytx_commission',$ytx_commission + 0);
		$this->assign('sqtx_commission',$sqtx_commission + 0);
		$this->assign('cantx_commission',$cantx_commission + 0);
		$this->assign('username',$username);
		$this->display('account');
	}

	// 代理中心
	public function agentCenter()
	{
		$uid = I('uid',0,'intval');		// 用户ID
		$downLayer = I('downLayer',0,'intval');		// 下线层级
		if (!$uid)
		{
			// 没有ID 默认为直属下线
			$uid = $this->uid;
			$downLayer = 1;
		} else {
			// 获取当前用户名
			$userInfo = $this->model->getMemberInfoById($uid,'username');
			$username = $userInfo['username'];
		}

		// 非总代
		if (!$this->info['super_agent'])
		{
			// 无下级标记
			if (!$downLayer)
			{
				$this->error('错误参数，操作非法！',U('Home/User/agentCenter'));
			}
			// 普通会员只能查看三级下线
			if ($downLayer > 3)
			{
				$this->error('只能查看三级下线会员',U('Home/User/agentCenter'));
			}
		}

		if (IS_AJAX)
		{
			// AJAX 加载更多
			$page = I('page',2,'intval');	// 页码
			// 非二页以上
			if ($page >= 2)
			{
				$user_list = $this->model->getDownMember($uid, $page);
				$this->ajaxReturn(array('status' => '1', 'page' => $page + 1, 'user_list' => $user_list));
			}
			else
			{
				$this->ajaxReturn(array('status' => '-1'));
			}
		}
		
		//判断会员是否在试用期
		$judge_member =  judge_member_probation($this->opt,$this->info);
		
		// 非会员不能查看下级
		if ($this->info['level'] != 0 || $judge_member) {
			$user_list = $this->model->getDownMember($uid);
		}


		$this->assign(array(
			'uid' => $uid,
			'username' => $username,	// 当前会员名
			'downLayer' => $downLayer + 1,
			'user_list' => $user_list,
		));

		$this->display('agentCenter');
	}

	// 上级代理
	public function upstream()
	{
		$this->display('upstream');
	}
	
	// 删除会员
	/*public function deleteUser()
	{
		if (!IS_AJAX) {
			$this->error('错误操作！',U('Home/Index/index'));
		}
		// 操作用户是否拥有权限
		$superAgent = $this->model->where(array('id' => $this->uid))->getField('super_agent');
		if ($superAgent != 1) {
			$this->error('错误操作！',U('Home/Index/index'));
		}

		$uid = I('uid',0,'intval');
		// 检查删除对象是否为会员
		$userLevel = $this->model->where(array('id' => $uid))->getField('level');

		if ($userLevel) {
			$this->ajaxReturn(array('status' => 0, 'msg' => '不能删除会员'));
		} else {
			$result = $this->model->deleteUser($uid);
			if ($result) {
				$this->ajaxReturn(array('status' => 1, 'msg' => '删除非会员成功'));
			} else {
				$this->ajaxReturn(array('status' => 0, 'msg' => '删除非会员失败'));
			}
		}
	}*/

	//是否开启推广链接里的二维码
	public function openQrcode(){
		$uid = session('home_uid');
		$close_qr = I('open_qrcode');
 		
		$qr = M("ArticleQr")->where("user_id = {$uid}")->find();
		
		if(IS_POST){
			$data=array(
				'user_id'=>$uid,
				'close_qr'=>$close_qr,
			);
			
			if(empty($qr)){
				$_qr = M("ArticleQr")->add($data);
			}else{
				$_qr = M("ArticleQr")->where("user_id = {$uid}")->save($data);
			}
			
			if($_qr){

				$this->ajaxReturn(array('status'=>1,'msg'=>'提交成功','url'=>U('Home/User/people_centre')));

			}else{

				$this->ajaxReturn(array('status'=>0,'msg'=>'提交失败'));

			}
		}

		$this->assign('qr',$qr);
		$this->display('closeQr');
		
	}
}